package com.ddsso.auth.web.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.ddsso.auth.web.repository.LogoutDao;
import com.ddsso.auth.web.session.DistributedSession;
import com.ddsso.auth.web.util.AuthDesCoderUtil;
import com.ddsso.auth.web.util.BeanUtils;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zdd
 * @package com.ddsso.auth.web.filter
 * @Time Created by zdd on 2016/11/3.
 * @description 登出处理。包括远程redis的sessionid.customer中的特殊处理
 */
public class LogoutProcessFilter extends BaseFilter {
    private static final Logger logger = LoggerFactory.getLogger(LogoutProcessFilter.class);

    private String redirectUri = null;
    private String loginUri=null;
    private String logoutUri=null;
    private String propertyAuthId=null;
    @Autowired
    @Qualifier("logoutDao")
    private LogoutDao logoutDao;

    public void setRedirectUri(String redirectUri) {
        this.redirectUri = redirectUri;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain filterChain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        logger.info(request.getRequestURI()+":"+request.getServletPath());
        if (request.getServletPath().endsWith("logout.action")||request.getRequestURI().endsWith("logout")) {
            doAuthLogout(request,response);
            response.sendRedirect(redirectUri);
        }else{
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }

    public void setLoginUri(String loginUri) {
        this.loginUri = loginUri;
    }

    public void setLogoutUri(String logoutUri) {
        this.logoutUri = logoutUri;
    }

    public void setPropertyAuthId(String propertyAuthId) {
        this.propertyAuthId = propertyAuthId;
    }

    /**
     * @description 远程状态登出
     * @param request
     * @param response
     * @return
     */
    private String doAuthLogout(HttpServletRequest request,HttpServletResponse response){
        Session session= SecurityUtils.getSubject().getSession();
        Object loginAuth = session.getAttribute("");//从配置获取

        String loginTd=loginAuth!=null&& StringUtils.isNotBlank(propertyAuthId)?(String) BeanUtils.getFieldValueByName(propertyAuthId, loginAuth):"";
        String token=getCurrentCookieShareSession(request.getCookies());
        Map<String,String> params=new HashMap<String,String>();
        params.put("token",token);
        params.put("authId", loginTd);
        logoutDao.invalidSession(loginTd, token);
        Cookie cookie = new Cookie(SESSION_SHARE_SIGN, null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        request.setAttribute("token","");
        response.setHeader(ihomeHeaderToken,"");
        SecurityUtils.getSubject().logout();
        return "";

    }

    /**
     * @description 取出存储的cookie
     * @param cookies
     * @return
     */
    private String getCurrentCookieShareSession(Cookie[] cookies) {
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if (SESSION_SHARE_SIGN.equals(name)) {
                    if(cookie.getValue()!=null&&StringUtils.isNotBlank(cookie.getValue())){
                        try{
                            return AuthDesCoderUtil.desDecryptTokenOrSessionId(URLDecoder.decode(cookie.getValue(),"UTF-8"));
                        }catch (Exception e){
                            logger.info("取cookie出错..........");
                            return "";
                        }
                    }
                    return "";
                }
            }
        }
        return null;
    }
    private String ihomeHeaderToken = "ihome-token";
    private static String SESSION_SHARE_SIGN="SHARE_JSESSIONID";
}
